/**
 * @fileoverview �ٶȵ�ͼ�Ŀɸ��ݵ�ǰpoi���������ܱ߼������������ݳ���ѯ����Ϣ���ڣ����⿪�š�
 * ���������<a href="symbols/BMapLib.SearchInfoWindow.html">SearchInfoWindow</a>��
 * ����Baidu Map API 1.4��
 *
 * @author Baidu Map Api Group
 * @version 1.4
 */
/**
 * @namespace BMap������library�������BMapLib�����ռ���
 */
var BMapLib = window.BMapLib = BMapLib || {};
//������searchInfoWindow��ѡ��ļ�������
var BMAPLIB_TAB_SEARCH   = 0, BMAPLIB_TAB_TO_HERE  = 1, BMAPLIB_TAB_FROM_HERE  = 2;
(function() {
    //����baidu��
    var T, baidu = T = baidu || {version: '1.5.0'};
    baidu.guid = '$BAIDU$';
    //���·���Ϊ�ٶ�Tangram����еķ������뵽http://tangram.baidu.com �鿴�ĵ�
    (function() {
        window[baidu.guid] = window[baidu.guid] || {};

		baidu.lang = baidu.lang || {};
        baidu.lang.isString = function (source) {
            return '[object String]' == Object.prototype.toString.call(source);
        };
        baidu.lang.Event = function (type, target) {
            this.type = type;
            this.returnValue = true;
            this.target = target || null;
            this.currentTarget = null;
        };


        baidu.object = baidu.object || {};
        baidu.extend =
        baidu.object.extend = function (target, source) {
            for (var p in source) {
                if (source.hasOwnProperty(p)) {
                    target[p] = source[p];
                }
            }

            return target;
        };
        baidu.event = baidu.event || {};
        baidu.event._listeners = baidu.event._listeners || [];
        baidu.dom = baidu.dom || {};

        baidu.dom._g = function (id) {
            if (baidu.lang.isString(id)) {
                return document.getElementById(id);
            }
            return id;
        };
        baidu._g = baidu.dom._g;
        baidu.event.on = function (element, type, listener) {
            type = type.replace(/^on/i, '');
            element = baidu.dom._g(element);
            var realListener = function (ev) {
                    // 1. ���ﲻ֧��EventArgument,  ԭ���ǿ�frame���¼�����
                    // 2. element��Ϊ������this
                    listener.call(element, ev);
                },
                lis = baidu.event._listeners,
                filter = baidu.event._eventFilter,
                afterFilter,
                realType = type;
            type = type.toLowerCase();
            // filter����
            if(filter && filter[type]){
                afterFilter = filter[type](element, type, realListener);
                realType = afterFilter.type;
                realListener = afterFilter.listener;
            }

            // �¼�����������
            if (element.addEventListener) {
                element.addEventListener(realType, realListener, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + realType, realListener);
            }
            // ���������洢��������
            lis[lis.length] = [element, type, listener, realListener, realType];
            return element;
        };

        baidu.on = baidu.event.on;
        baidu.event.un = function (element, type, listener) {
            element = baidu.dom._g(element);
            type = type.replace(/^on/i, '').toLowerCase();

            var lis = baidu.event._listeners,
                len = lis.length,
                isRemoveAll = !listener,
                item,
                realType, realListener;
            while (len--) {
                item = lis[len];

                if (item[1] === type
                    && item[0] === element
                    && (isRemoveAll || item[2] === listener)) {
                   	realType = item[4];
                   	realListener = item[3];
                    if (element.removeEventListener) {
                        element.removeEventListener(realType, realListener, false);
                    } else if (element.detachEvent) {
                        element.detachEvent('on' + realType, realListener);
                    }
                    lis.splice(len, 1);
                }
            }

            return element;
        };
        baidu.un = baidu.event.un;
        baidu.dom.g = function (id) {
            if ('string' == typeof id || id instanceof String) {
                return document.getElementById(id);
            } else if (id && id.nodeName && (id.nodeType == 1 || id.nodeType == 9)) {
                return id;
            }
            return null;
        };
        baidu.g = baidu.G = baidu.dom.g;
        baidu.string = baidu.string || {};

        baidu.browser = baidu.browser || {};
        baidu.browser.ie = baidu.ie = /msie (\d+\.\d+)/i.test(navigator.userAgent) ? (document.documentMode || + RegExp['\x241']) : undefined;
        baidu.dom._NAME_ATTRS = (function () {
            var result = {
                'cellpadding': 'cellPadding',
                'cellspacing': 'cellSpacing',
                'colspan': 'colSpan',
                'rowspan': 'rowSpan',
                'valign': 'vAlign',
                'usemap': 'useMap',
                'frameborder': 'frameBorder'
            };

            if (baidu.browser.ie < 8) {
                result['for'] = 'htmlFor';
                result['class'] = 'className';
            } else {
                result['htmlFor'] = 'for';
                result['className'] = 'class';
            }

            return result;
        })();
        baidu.dom.setAttr = function (element, key, value) {
            element = baidu.dom.g(element);
            if ('style' == key){
                element.style.cssText = value;
            } else {
                key = baidu.dom._NAME_ATTRS[key] || key;
                element.setAttribute(key, value);
            }
            return element;
        };
         baidu.setAttr = baidu.dom.setAttr;
        baidu.dom.setAttrs = function (element, attributes) {
            element = baidu.dom.g(element);
            for (var key in attributes) {
                baidu.dom.setAttr(element, key, attributes[key]);
            }
            return element;
        };
        baidu.setAttrs = baidu.dom.setAttrs;
        baidu.dom.create = function(tagName, opt_attributes) {
            var el = document.createElement(tagName),
                attributes = opt_attributes || {};
            return baidu.dom.setAttrs(el, attributes);
        };

        baidu.cookie = baidu.cookie || {};


        baidu.cookie._isValidKey = function (key) {
            // http://www.w3.org/Protocols/rfc2109/rfc2109
            // Syntax:  General
            // The two state management headers, Set-Cookie and Cookie, have common
            // syntactic properties involving attribute-value pairs.  The following
            // grammar uses the notation, and tokens DIGIT (decimal digits) and
            // token (informally, a sequence of non-special, non-white space
            // characters) from the HTTP/1.1 specification [RFC 2068] to describe
            // their syntax.
            // av-pairs   = av-pair *(";" av-pair)
            // av-pair    = attr ["=" value] ; optional value
            // attr       = token
            // value      = word
            // word       = token | quoted-string
            
            // http://www.ietf.org/rfc/rfc2068.txt
            // token      = 1*<any CHAR except CTLs or tspecials>
            // CHAR       = <any US-ASCII character (octets 0 - 127)>
            // CTL        = <any US-ASCII control character
            //              (octets 0 - 31) and DEL (127)>
            // tspecials  = "(" | ")" | "<" | ">" | "@"
            //              | "," | ";" | ":" | "\" | <">
            //              | "/" | "[" | "]" | "?" | "="
            //              | "{" | "}" | SP | HT
            // SP         = <US-ASCII SP, space (32)>
            // HT         = <US-ASCII HT, horizontal-tab (9)>
                
            return (new RegExp("^[^\\x00-\\x20\\x7f\\(\\)<>@,;:\\\\\\\"\\[\\]\\?=\\{\\}\\/\\u0080-\\uffff]+\x24")).test(key);
        };

        baidu.cookie.getRaw = function (key) {
            if (baidu.cookie._isValidKey(key)) {
                var reg = new RegExp("(^| )" + key + "=([^;]*)(;|\x24)"),
                    result = reg.exec(document.cookie);
                    
                if (result) {
                    return result[2] || null;
                }
            }

            return null;
        };

        baidu.cookie.get = function (key) {
            var value = baidu.cookie.getRaw(key);
            if ('string' == typeof value) {
                value = decodeURIComponent(value);
                return value;
            }
            return null;
        };

        baidu.cookie.setRaw = function (key, value, options) {
            if (!baidu.cookie._isValidKey(key)) {
                return;
            }
            
            options = options || {};
            //options.path = options.path || "/"; // meizz 20100402 �趨һ����ʼֵ����������Ĳ���
            //berg 20100409 ȥ������Ϊ�û�ϣ��Ĭ�ϵ�path�ǵ�ǰ·�����������������cookie�Ķ���Ҳ��һ�µ�
            
            // ����cookie����ʱ��
            var expires = options.expires;
            if ('number' == typeof options.expires) {
                expires = new Date();
                expires.setTime(expires.getTime() + options.expires);
            }
            
            document.cookie =
                key + "=" + value
                + (options.path ? "; path=" + options.path : "")
                + (expires ? "; expires=" + expires.toGMTString() : "")
                + (options.domain ? "; domain=" + options.domain : "")
                + (options.secure ? "; secure" : ''); 
        };

        baidu.cookie.set = function (key, value, options) {
            baidu.cookie.setRaw(key, encodeURIComponent(value), options);
        };

        baidu.cookie.remove = function (key, options) {
            options = options || {};
            options.expires = new Date(0);
            baidu.cookie.setRaw(key, '', options);
        };// �������

        //�����Ƿ�����ȷ���ֻ���
        baidu.isPhone =  function(phone) {
            return /\d{11}/.test(phone);
        }

        //�����Ƿ�����ȷ�ļ�����
        baidu.isActivateCode =  function(vcode) {
            return /\d{4}/.test(vcode);
        }


        T.undope=true;
    })();

    /**
     * @exports SearchInfoWindow as BMapLib.SearchInfoWindow
     */

    var SearchInfoWindow =
        /**
         * SearchInfoWindow��Ĺ��캯��
         * @class SearchInfoWindow <b>���</b>��
         * ���Զ������ģ�档
         * @constructor
         * @param {Map} map Baidu map��ʵ������.
         * @param {String} content searchInfoWindow�е�����,֧��HTML����.
         * @param {Json Object} opts ��ѡ������������Ǳ����������ѡ�������<br />
         * {<br />"<b>title</b>" : {String} searchInfoWindow�ı������ݣ�֧��HTML����<br/>
         * {<br />"<b>width</b>" : {Number} searchInfoWindow�����ݿ��<br/>
         * {<br />"<b>height</b>" : {Number} searchInfoWindow�����ݸ߶� <br/>
         * {<br />"<b>offset</b>" : {Size} searchInfoWindow��ƫ����<br/>
         * <br />"<b>enableAutoPan</b>" : {Boolean} �Ƿ������Զ�ƽ�ƹ���,Ĭ�Ͽ���    <br />
         * <br />"<b>panel</b>" : {String} ����չ�ּ�����Ϣ�����,������domԪ�ػ�Ԫ�ص�IDֵ <br />
         * <br />"<b>searchTypes</b>" : {Array} ͨ�������������ü�������Tabѡ�������ѡ���ѡ��ѡ�˳��Ҳ���������˳�������򣬴������������ʾ����ģ�棬�����ô˲�����Ĭ������ѡ�����ʾ������ɴ����ֵΪ������BMAPLIB_TAB_SEARCH<�ܱ߼���>, BMAPLIB_TAB_TO_HERE<��ȥ����>, BMAPLIB_TAB_FROM_HERE<���������>  <br />
         * <br />"<b>enableSendToPhone</b>" : {Boolean} �Ƿ��������͵��ֻ�����,Ĭ�Ͽ���    <br />
         * }<br />.
         * @example <b>�ο�ʾ����</b><br />
         * var searchInfoWindow = new BMapLib.SearchInfoWindow(map,"�ٶȵ�ͼapi",{
         *     title "�ٶȴ���",
         *     width  : 280,
         *     height : 50,
         *     panel  : "panel", //����������
         *     enableAutoPan : true, //�Զ�ƽ��
         *     enableSendToPhone : true, //�Ƿ��������͵��ֻ�����
         *     searchTypes :[
         *         BMAPLIB_TAB_SEARCH,   //�ܱ߼���
         *         BMAPLIB_TAB_TO_HERE,  //������ȥ
         *         BMAPLIB_TAB_FROM_HERE //���������
         *     ]
         * });
         */
        BMapLib.SearchInfoWindow = function(map, content, opts) {

        //�洢��ǰʵ��
        this.guid = guid++;
        BMapLib.SearchInfoWindow.instance[this.guid] = this;

        this._isOpen = false;
        this._map = map;

        this._opts = opts   = opts || {};
        this._content = content || "";
        this._opts.width          = opts.width;
        this._opts.height         = opts.height;
        this._opts._title         = opts.title || "";
        this._opts.offset         = opts.offset || new BMap.Size(0,0);
        this._opts.enableAutoPan  = opts.enableAutoPan === false? false : true;
        this._opts._panel         = opts.panel || null;
        this._opts._searchTypes   = opts.searchTypes; //����������ʽ
        this._opts.enableSendToPhone = opts.enableSendToPhone; //�Ƿ������͵��ֻ�
    }
    SearchInfoWindow.prototype = new BMap.Overlay();
    SearchInfoWindow.prototype.initialize = function(map) {
        this._closeOtherSearchInfo();
        var me = this;

        var div = this._createSearchTemplate();

        var floatPane = map.getPanes().floatPane;
        floatPane.style.width = "auto";
        floatPane.appendChild(div);
        this._initSearchTemplate();
        //���������ݺ󣬻�ȡdiv�Ŀ��,�߶�
        this._getSearchInfoWindowSize();
        this._boxWidth = parseInt(this.container.offsetWidth,10);
        this._boxHeight = parseInt(this.container.offsetHeight,10);
        //��ֹ����ð���¼�
        baidu.event.on(div,"onmousedown",function(e){
            me._stopBubble(e);
        });
        baidu.event.on(div,"onmouseover",function(e){
            me._stopBubble(e);
        });
        baidu.event.on(div,"click",function(e){
            me._stopBubble(e);
        });
        baidu.event.on(div,"dblclick",function(e){
            me._stopBubble(e);
        });
        return div;
    }
    SearchInfoWindow.prototype.draw = function() {
        this._isOpen && this._adjustPosition(this._point);
    }
    /**
     * ��searchInfoWindow
     * @param {Marker|Point} location Ҫ���ĸ�marker����point�ϴ�searchInfoWindow
     * @return none
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.open();
     */
    SearchInfoWindow.prototype.open = function(anchor){
        this._map.closeInfoWindow();
        var me = this,poi;
        if(!this._isOpen) {
            this._map.addOverlay(this);
            this._isOpen = true;
            //�ӳ�10ms�ɷ�open�¼���ʹ��󶨵��¼����Դ�����
            setTimeout(function(){
                me._dispatchEvent(me,"open",{"point" : me._point});
            },10);
        }
        if(anchor instanceof BMap.Point){
            poi = anchor;
            //���֮ǰ���ڵ�marker�¼��󶨣�������ڵĻ�
            this._removeMarkerEvt();
            this._marker = null;
        }else if(anchor instanceof BMap.Marker){
        	//�����ǰmarker��Ϊ�գ�˵���ǵڶ���marker�����ߵڶ��ε�open��ť,���Ƴ���֮ǰ�󶨵��¼�
        	if(this._marker){
        		this._removeMarkerEvt();
        	}
            poi = anchor.getPosition();
            this._marker = anchor;
            !this._markerDragend && this._marker.addEventListener("dragend",this._markerDragend = function(e){
            	me._point = e.point;
            	me._adjustPosition(me._point);
            	me._panBox();
            	me.show();
            });
             //��marker��dragging�¼����϶�marker��ʱ��searchInfoWindowҲ�����ƶ�
            !this._markerDragging && this._marker.addEventListener("dragging",this._markerDragging = function(){
            	me.hide();
            	me._point = me._marker.getPosition();
                me._adjustPosition(me._point);
            });
        }
        //�򿪵�ʱ�򣬽�infowindow��ʾ
        this.show();
        this._point = poi;
        this._panBox();
        this._adjustPosition(this._point);
    }
    /**
     * �ر�searchInfoWindow
     * @return none
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.close();
     */
    SearchInfoWindow.prototype.close = function(){
        if(this._isOpen){
            this._map.removeOverlay(this);
            this._disposeAutoComplete();
            this._isOpen = false;
            this._dispatchEvent(this,"close",{"point" : this._point});
        }
    }

	/**
   	 * ��searchInfoWindowʱ���ɷ��¼��Ľӿ�
     * @name SearchInfoWindow#Open
     * @event
     * @param {Event Object} e �ص������᷵��event�������������·���ֵ��
     * <br />{"<b>target</b> : {BMap.Overlay} �����¼���Ԫ��,
     * <br />"<b>type</b>��{String} �¼�����,
     * <br />"<b>point</b>��{Point} searchInfoWindow�Ĵ�λ��}
     *
     * @example <b>�ο�ʾ����</b>
     * searchInfoWindow.addEventListener("open", function(e) {
     *     alert(e.type);
     * });
     */
   /**
   	 * �ر�searchInfoWindowʱ���ɷ��¼��Ľӿ�
     * @name SearchInfoWindow#Close
     * @event
     * @param {Event Object} e �ص������᷵��event�������������·���ֵ��
     * <br />{"<b>target</b> : {BMap.Overlay} �����¼���Ԫ��,
     * <br />"<b>type</b>��{String} �¼�����,
     * <br />"<b>point</b>��{Point} searchInfoWindow�Ĺر�λ��}
     *
     * @example <b>�ο�ʾ����</b>
     * searchInfoWindow.addEventListener("close", function(e) {
     *     alert(e.type);
     * });
     */
  /**
     * �����Զ�ƽ��
     * @return none
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.enableAutoPan();
     */
    SearchInfoWindow.prototype.enableAutoPan = function(){
        this._opts.enableAutoPan = true;
    }
    /**
     * �����Զ�ƽ��
     * @return none
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.disableAutoPan();
     */
    SearchInfoWindow.prototype.disableAutoPan = function(){
        this._opts.enableAutoPan = false;
    }
    /**
     * ����searchInfoWindow������
     * @param {String|HTMLElement} content ���������е����ݣ�֧��HTML��ʽ
     * @return none
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.setContent("�ٶȵ�ͼAPI");
     */
    SearchInfoWindow.prototype.setContent = function(content){
      	this._setContent(content);
      	this._getSearchInfoWindowSize();
        this._adjustPosition(this._point);
    },
    /**
     * ����searchInfoWindow������
     * @param {String|HTMLElement} title ���������е����ݣ�֧��HTML��ʽ
     * @return none
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.setTitle("�ٶȵ�ͼAPI");
     */
    SearchInfoWindow.prototype.setTitle = function(title){
        this.dom.title.innerHTML = title;
        this._opts._title = title;
    }
    /**
     * ��ȡsearchInfoWindow������
     * @return {String} String
     *
     * @example <b>�ο�ʾ����</b><br />
     * alret(searchInfoWindow.getContent());
     */
    SearchInfoWindow.prototype.getContent = function(){
        return this.dom.content.innerHTML;
    },
    /**
     * ��ȡsearchInfoWindow�ı���
     * @return {String} String
     *
     * @example <b>�ο�ʾ����</b><br />
     * alert(searchInfoWindow.getTitle());
     */
    SearchInfoWindow.prototype.getTitle = function(){
        return this.dom.title.innerHTML;
    }
    /**
     * ������Ϣ���ĵ���λ��
     * @param {Point} point ����position
     * @return none
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.setPosition(new BMap.Point(116.35,39.911));
     */
    SearchInfoWindow.prototype.setPosition = function(poi){
        this._point = poi;
        this._adjustPosition(poi);
        this._panBox();
        this._removeMarkerEvt();
    }
    /**
     * �����Ϣ���ĵ���λ��
     * @return {Point} ��Ϣ���ĵ�������
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.getPosition();
     */
    SearchInfoWindow.prototype.getPosition = function(){
        return this._point;
    }
    /**
     * ������Ϣ���ڵļ�ͷ������Ϣ�����ڵ�ͼ
     * ����ê���ĵ�������������ƫ������
     * @return {Size} Size
     *
     * @example <b>�ο�ʾ����</b><br />
     * searchInfoWindow.getOffset();
     */
    SearchInfoWindow.prototype.getOffset = function(){
        return this._opts.offset;
    },

    baidu.object.extend(SearchInfoWindow.prototype,{
        /**
         * ������Ļֻ��һ��searchInfoWindow,�ر������Ѵ򿪵�searchInfoWindow
         */
        _closeOtherSearchInfo: function () {
            var instance = BMapLib.SearchInfoWindow.instance,
                len      = instance.length;
            while (len--) {
                if (instance[len]._isOpen) {
                    instance[len].close();
                }
            }
        },

        /**
	     * ����searchInfoWindow������
	     * @param {String|HTMLElement} content ���������е�����
	     * @return none
	     *
	     * @example <b>�ο�ʾ����</b><br />
	     * searchInfoWindow.setContent("�ٶȵ�ͼAPI");
	     */
        _setContent: function(content){
	        if(!this.dom || !this.dom.content){
	            return;
	        }
	        //string���͵�content
	        if(typeof content.nodeType === "undefined"){
	            this.dom.content.innerHTML = content;
	        }else{
	            this.dom.content.appendChild(content);
	        }

            var me = this;
            me._adjustContainerWidth();

	        this._content = content;
   	    },
        /**
         * ����searchInfoWindow��position
         * @return none
         */
        _adjustPosition: function(poi){
            var pixel = this._getPointPosition(poi);
            var icon = this._marker && this._marker.getIcon();
            if(this._marker){
                this.container.style.bottom = -(pixel.y - this._opts.offset.height - icon.anchor.height + icon.infoWindowAnchor.height) - this._marker.getOffset().height + 2 + 30 + "px";
                this.container.style.left = pixel.x - icon.anchor.width + this._marker.getOffset().width + icon.infoWindowAnchor.width - this._boxWidth / 2 + 28 + "px";
            }else{
                this.container.style.bottom = -(pixel.y - this._opts.offset.height) + 30 + "px";
                this.container.style.left = pixel.x - this._boxWidth / 2 + 25 + "px";
            }
        },
        /**
         * �õ�searchInfoWindow��position
         * @return Point  searchInfoWindow��ǰ��position
         */
        _getPointPosition: function(poi){
            this._pointPosition = this._map.pointToOverlayPixel(poi);
            return this._pointPosition;
        },
        /**
         * �õ�searchInfoWindow�ĸ߶ȸ����
         * @return none
         */
        _getSearchInfoWindowSize: function(){
        	this._boxWidth = parseInt(this.container.offsetWidth,10);
        	this._boxHeight = parseInt(this.container.offsetHeight,10);
        },
        /**
         * ��ֹ�¼�ð��
         * @return none
         */
        _stopBubble: function(e){
            if(e && e.stopPropagation){
                e.stopPropagation();
            }else{
                window.event.cancelBubble = true;
            }
        },
        /**
         * �Զ�ƽ��searchInfoWindow��ʹ������Ұ��ȫ����ʾ
         * @return none
         */
        _panBox: function(){
            if(!this._opts.enableAutoPan){
                return;
            }
            var mapH = parseInt(this._map.getContainer().offsetHeight,10),
                mapW = parseInt(this._map.getContainer().offsetWidth,10),
                boxH = this._boxHeight,
                boxW = this._boxWidth;
            //searchInfoWindow���ڱ���Ŀ�Ȼ��߸߶ȳ���map container
            if(boxH >= mapH || boxW >= mapW){
                return;
            }
            //���point���ڿ���������
            if(!this._map.getBounds().containsPoint(this._point)){
                this._map.setCenter(this._point);
            }
            var anchorPos = this._map.pointToPixel(this._point),
                panTop,panY,
                //��೬��
                panLeft  = boxW / 2 - 28 - anchorPos.x + 10,
                //�Ҳ೬��
                panRight = boxW / 2 + 28 + anchorPos.x - mapW + 10;
            if(this._marker){
                var icon = this._marker.getIcon();
            }

            //�ϲ೬��
            var h = this._marker ? icon.anchor.height + this._marker.getOffset().height - icon.infoWindowAnchor.height : 0;
            panTop = boxH - anchorPos.y + this._opts.offset.height + h + 31 + 10;

            panX = panLeft > 0 ? panLeft : (panRight > 0 ? -panRight : 0);
            panY = panTop > 0 ? panTop : 0;
            this._map.panBy(panX,panY);
        },
        _removeMarkerEvt: function(){
			this._markerDragend && this._marker.removeEventListener("dragend", this._markerDragend);
            this._markerDragging && this._marker.removeEventListener("dragging", this._markerDragging);
            this._markerDragend = this._markerDragging = null;
        },
      	/**
	     * �����ɷ��¼�����
	     *
	     * @private
	     * @param {Object} instance �ɷ��¼���ʵ��
	     * @param {String} type �ɷ����¼���
	     * @param {Json} opts �ɷ��¼�����ӵĲ�������ѡ
	     */
	    _dispatchEvent: function(instance, type, opts) {
	        type.indexOf("on") != 0 && (type = "on" + type);
	        var event = new baidu.lang.Event(type);
	        if (!!opts) {
	            for (var p in opts) {
	                event[p] = opts[p];
	            }
	        }
	        instance.dispatchEvent(event);
	    },

        /**
         * ����infowindowģ��ĳ�ʼ������
         */
        _initSearchTemplate: function() {
            this._initDom();
            this._initPanelTemplate();
            this.setTitle(this._opts._title);
            if (this._opts.height) {
                this.dom.content.style.height = parseInt(this._opts.height, 10) + "px";
            }
            this._setContent(this._content);
            this._initService();
            this._bind();
            if (this._opts._searchTypes) {
                this._setSearchTypes();
            }
            this._mendIE6();
        },

        /**
         * ��������ģ��
         * @return dom
         */
        _createSearchTemplate: function() {
            if (!this._div) {
                var div = baidu.dom.create('div', {
                    "class" : "BMapLib_SearchInfoWindow",
                    "id"    : "BMapLib_SearchInfoWindow" + this.guid
                });
                var template = [
                    '<div class="BMapLib_bubble_top">',
                        '<div class="BMapLib_bubble_title" id="BMapLib_bubble_title' + this.guid + '"></div>',
                        '<div class="BMapLib_bubble_tools">',
                            '<div class="BMapLib_bubble_close" title="�ر�" id="BMapLib_bubble_close' + this.guid + '">',
                            '</div>',
                            '<div class="BMapLib_sendToPhone" style="display:none" id="BMapLib_sendToPhone' + this.guid + '">',
                            '</div>',
                        '</div>',
                    '</div>',
                    '<div class="BMapLib_bubble_center">',
                        '<div class="BMapLib_bubble_content" id="BMapLib_bubble_content' + this.guid + '">',
                        '</div>',
                        '<div class="BMapLib_nav" style="display:none" id="BMapLib_nav' + this.guid + '">',
                            '<ul class="BMapLib_nav_tab" id="BMapLib_nav_tab' + this.guid + '">', //tabѡ�
                                '<li class="BMapLib_first BMapLib_current" id="BMapLib_tab_search' + this.guid + '" style="display:block;">',
                                    '<span class="BMapLib_icon BMapLib_icon_nbs"></span>�ڸ�����',
                                '</li>',
                                '<li class="" id="BMapLib_tab_tohere' + this.guid + '" style="display:block;">',
                                    '<span class="BMapLib_icon BMapLib_icon_tohere"></span>������ȥ',
                                '</li>',
                                '<li class="" id="BMapLib_tab_fromhere' + this.guid + '" style="display:block;">',
                                    '<span class="BMapLib_icon BMapLib_icon_fromhere"></span>���������',
                                '</li>',
                            '</ul>',
                            '<ul class="BMapLib_nav_tab_content">', //tab����
                                '<li id="BMapLib_searchBox' + this.guid + '">',
                                    '<table width="100%" align="center" border=0 cellpadding=0 cellspacing=0>',
                                        '<tr><td style="padding-left:8px;"><input id="BMapLib_search_text' + this.guid + '" class="BMapLib_search_text" type="text" maxlength="100" autocomplete="off"></td><td width="55" style="padding-left:7px;"><input id="BMapLib_search_nb_btn' + this.guid + '" type="submit" value="����" class="iw_bt"></td></tr>',
                                    '</table>',
                                '</li>',
                                '<li id="BMapLib_transBox' + this.guid + '" style="display:none">',
                                    '<table width="100%" align="center" border=0 cellpadding=0 cellspacing=0>',
                                        '<tr><td width="30" style="padding-left:8px;"><div id="BMapLib_stationText' + this.guid + '">���</div></td><td><input id="BMapLib_trans_text' + this.guid + '" class="BMapLib_trans_text" type="text" maxlength="100" autocomplete="off"></td><td width="106" style="padding-left:7px;"><input id="BMapLib_search_bus_btn' + this.guid + '" type="button" value="����" class="iw_bt" style="margin-right:5px;"><input id="BMapLib_search_drive_btn' + this.guid + '" type="button" class="iw_bt" value="�ݳ�"></td></tr>',
                                    '</table>',
                                '</li>',
                            '</ul>',
                        '</div>',
                    '</div>',
                    '<div class="BMapLib_bubble_bottom"></div>',
                    '<img src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/iw_tail.png" width="58" height="31" alt="" class="BMapLib_trans" id="BMapLib_trans' + this.guid + '" style="left:144px;"/>'
                ];
                div.innerHTML = template.join("");
                this._div = div;
            }
            return this._div;
        },

        /**
         * �������
         */
        _initPanelTemplate: function() {
            var panel = baidu.g(this._opts._panel);
            if (!this.dom.panel && panel) {
                panel.innerHTML = "";
                this.dom.panel = panel;
                //����ַѡ��ҳ�õ���ʾ����
                var address = baidu.dom.create('div');
                address.style.cssText = "display:none;background:#FD9;height:30px;line-height:30px;text-align:center;font-size:12px;color:#994C00;";
                panel.appendChild(address);
                this.dom.panel.address = address;
                //����ַ���������
                var localSearch = baidu.dom.create('div');
                panel.appendChild(localSearch);
                this.dom.panel.localSearch = localSearch;
            }
        },

        /**
         * ��ȡ��ص�DOMԪ��
         */
        _initDom: function () {
            if (!this.dom) {
                this.dom = {
                    container     : baidu.g("BMapLib_SearchInfoWindow" + this.guid) //����
                    , content     : baidu.g("BMapLib_bubble_content" + this.guid)   //������
                    , title       : baidu.g("BMapLib_bubble_title" + this.guid)     //����
                    , closeBtn    : baidu.g("BMapLib_bubble_close" + this.guid)     //�رհ�ť
                    , transIco    : baidu.g("BMapLib_trans" + this.guid)            //infowindow����������
                    , navBox      : baidu.g("BMapLib_nav" + this.guid)              //��������
                    , navTab      : baidu.g("BMapLib_nav_tab" + this.guid)          //tab����
                    , seartTab    : baidu.g("BMapLib_tab_search" + this.guid)       //�ڸ�����tab
                    , tohereTab   : baidu.g("BMapLib_tab_tohere" + this.guid)       //������ȥtab
                    , fromhereTab : baidu.g("BMapLib_tab_fromhere" + this.guid)     //���������tab
                    , searchBox   : baidu.g("BMapLib_searchBox" + this.guid)        //��ͨ��������
                    , transBox    : baidu.g("BMapLib_transBox" + this.guid)         //�����ݳ���������������������͵�����ȥ����һ������
                    , stationText : baidu.g("BMapLib_stationText" + this.guid)      //�����յ��ı�
                    , nbBtn       : baidu.g("BMapLib_search_nb_btn" + this.guid)    //��ͨ������ť
                    , busBtn      : baidu.g("BMapLib_search_bus_btn" + this.guid)   //�����ݳ�������ť
                    , driveBtn    : baidu.g("BMapLib_search_drive_btn" + this.guid) //�ݳ�������ť
                    , searchText  : baidu.g("BMapLib_search_text" + this.guid)      //��ͨ�����ı���
                    , transText   : baidu.g("BMapLib_trans_text" + this.guid)       //�����ݳ������ı���
                    , sendToPhoneBtn : baidu.g("BMapLib_sendToPhone" + this.guid)      //���͵��ֻ�
                }
                this.container = this.dom.container;
            }
        },

        /**
         * ����infowindow���ݵĿ��
         */
        _adjustContainerWidth: function() {
            var width = 100,
                height = 0;
            if (this._opts.width) {
                width = parseInt(this._opts.width, 10);
                width += 10;
            } else {
                width = parseInt(this.dom.content.offsetWidth, 10);
            }
            if (width < 100) {
                width = 100;
            }

            this._width = width;
            //����container�Ŀ��
            this.container.style.width = this._width + "px";
            this._adjustTransPosition();
        },

        /**
         * ����infowindow�������ε�λ��
         */
        _adjustTransPosition: function() {
            //���������ε�λ��
            this.dom.transIco.style.left = this.container.offsetWidth / 2 - 2 - 29 + "px";
            this.dom.transIco.style.top = this.container.offsetHeight - 2 + "px";
        },

        /**
         * ��ʼ������������
         */
        _initService: function () {
            var map  = this._map;
            var me = this;
            var renderOptions = {}
            renderOptions.map = map;

            if (this.dom.panel) {
                renderOptions.panel = this.dom.panel.localSearch;
            }

            if (!this.localSearch) {
                this.localSearch = new BMap.LocalSearch(map, {
                    renderOptions: renderOptions
                    , onSearchComplete : function (result) {
                        me._clearAddress();
                        me._drawCircleBound();
                    }
                });
            }

            if (!this.transitRoute) {
                this.transitRoute = new BMap.TransitRoute(map, {
                    renderOptions: renderOptions
                    , onSearchComplete : function (results) {
                        me._transitRouteComplete(me.transitRoute, results);
                    }
                });
            }

            if (!this.drivingRoute) {
                this.drivingRoute  = new BMap.DrivingRoute(map, {
                    renderOptions: renderOptions
                    , onSearchComplete : function (results) {
                        me._transitRouteComplete(me.drivingRoute, results);
                    }
                });
            }
        },

        /**
         * ���¼�
         */
        _bind: function () {
            var me  = this;

            //�رհ�ť
            baidu.on(this.dom.closeBtn, "click", function(e) {
                me.close();
            });

            //���͵��ֻ���ť
            baidu.on(this.dom.sendToPhoneBtn, "click", function(e) {
                me._sendToPhone();
            });

            //�ܱ߼���tab��
            baidu.on(this.dom.seartTab, "click", function(e) {
                me._showTabContent(BMAPLIB_TAB_SEARCH);
            });

            //������ȥtab
            baidu.on(this.dom.tohereTab, "click", function(e) {
                me._showTabContent(BMAPLIB_TAB_TO_HERE);
            });

            //���������tab
            baidu.on(this.dom.fromhereTab, "click", function(e) {
                me._showTabContent(BMAPLIB_TAB_FROM_HERE);
            });

            //�ܱ߼�����ť
            baidu.on(this.dom.nbBtn, "click", function(e) {
                me._localSearchAction();
            });

            //����������ť
            baidu.on(this.dom.busBtn, "click", function(e) {
                me._transitRouteAction(me.transitRoute);
            });

            //�ݳ�������ť
            baidu.on(this.dom.driveBtn, "click", function(e) {
                me._transitRouteAction(me.drivingRoute);
            });

            //�ı����Զ������ʾ
            this._autoCompleteIni();

            if (this._opts.enableSendToPhone === false) {
                this.dom.sendToPhoneBtn.style.display = 'none';
            }
        },

        /**
         * ��ʾtab����
         */
        _showTabContent: function(type) {
            this._hideAutoComplete();
            var tabs = this.dom.navTab.getElementsByTagName("li"),
                len = tabs.length;
            
            for (var i = 0, len = tabs.length; i < len; i++) {
                tabs[i].className = "";
            }

            //��ʾ��ǰtab content������tab
            switch (type) {
                case BMAPLIB_TAB_SEARCH:
                    this.dom.seartTab.className      = "BMapLib_current";
                    this.dom.searchBox.style.display = "block";
                    this.dom.transBox.style.display  = "none";
                    break;
                case BMAPLIB_TAB_TO_HERE:
                    this.dom.tohereTab.className     = "BMapLib_current";
                    this.dom.searchBox.style.display = "none";
                    this.dom.transBox.style.display  = "block";
                    this.dom.stationText.innerHTML   = "���";
                    this._pointType = "endPoint";
                    break;
                case BMAPLIB_TAB_FROM_HERE:
                    this.dom.fromhereTab.className   = "BMapLib_current";
                    this.dom.searchBox.style.display = "none";
                    this.dom.transBox.style.display  = "block";
                    this.dom.stationText.innerHTML   = "�յ�";
                    this._pointType = "startPoint";
                    break;
            }

            this._firstTab.className += " BMapLib_first";
        },

        /**
         * ���Զ�����¼�
         */
        _autoCompleteIni: function () {
            this.searchAC= new BMap.Autocomplete({
                "input"      : this.dom.searchText
                , "location" : this._map
            });
            this.transAC = new BMap.Autocomplete({
                "input"      : this.dom.transText
                , "location" : this._map
            });
        },

        /**
         * �ر�autocomplete
         */
        _hideAutoComplete: function () {
            this.searchAC.hide();
            this.transAC.hide();
        },

        /**
         * ����autoComplete����
         */
        _disposeAutoComplete: function() {
        	if(this.searchAC.dispose)
        		this.searchAC.dispose();
        	if(this.transAC.dispose)
        		this.transAC.dispose();
        },

        /**
         * ����localsearch�¼�
         */
        _localSearchAction: function() {
            var kw = this._kw = this.dom.searchText.value;
            if (kw == "") {
                //����Ƿ�Ϊ��
                this.dom.searchText.focus();
            } else{
                this._reset();
                this.close();
                var radius  = this._radius = 1000;
                this.localSearch.searchNearby(kw, this._point, radius);
            }
        },

        /**
         * ���ܱ߼�����Բ��Ȧ
         */
        _drawCircleBound: function() {
            this._closeCircleBound();
            var circle = this._searchCircle = new BMap.Circle(this._point, this._radius, {
                strokeWeight: 3,
                strokeOpacity: 0.4,
                strokeColor: "#e00",
                filColor: "#00e",
                fillOpacity:0.4
            });

            var label = this._searchLabel = new RadiusToolBar(this._point, this.guid);

            this._map.addOverlay(circle);
            this._map.addOverlay(label);
            this._hasCircle = true;
        },

        /**
         * �޸��ܱ߼����İ뾶
         */
        _changeSearchRadius: function() {
            var radius = parseInt(baidu.g("BMapLib_search_radius" + this.guid).value, 10);
            if (radius > 0 && radius != this._radius) {
                this._radius = radius;
                this.localSearch.searchNearby(this._kw, this._point, radius);
                this._closeCircleBound();
            }
        },

        /**
         * �ر��ܱ߼�����Բ��Ȧ
         */
        _closeCircleBound: function(radius) {
            if (this._searchCircle) {
                this._map.removeOverlay(this._searchCircle);
            }
            if (this._searchLabel) {
                this._map.removeOverlay(this._searchLabel);
            }
            this._hasCircle = false;
        },

        /**
         * �����ݳ�������ѯ
         */
        _transitRouteAction: function (transitDrive) {
            var kw = this.dom.transText.value;
            if (kw == "") {
                //����Ƿ�Ϊ��
                this.dom.transText.focus();
            } else {
                this._reset();
                this.close();
                var transPoi = this._getTransPoi(kw);
                transitDrive.search(transPoi.start, transPoi.end);
            }
        },

        /**
         * �����ݳ���ѯ��������
         */
        _transitRouteComplete: function(transitDrive, results) {
            this._clearAddress();
            var status = transitDrive.getStatus();
            //�������δ֪�����
            if (status == BMAP_STATUS_UNKNOWN_ROUTE) {
                var startStatus = results.getStartStatus(),
                    endStatus   = results.getEndStatus(),
                    tip         = "";
                tip = "�Ҳ�����ص���·";
                if (startStatus == BMAP_ROUTE_STATUS_EMPTY && endStatus == BMAP_ROUTE_STATUS_EMPTY) {
                    tip = "�Ҳ�����ص������յ�";
                } else {
                    if (startStatus == BMAP_ROUTE_STATUS_EMPTY) {
                        tip = "�Ҳ�����ص����";
                    }
                    if (endStatus == BMAP_ROUTE_STATUS_EMPTY) {
                        tip = "�Ҳ�����ص��յ�";
                    }
                }
                //��ǰ�����ĵ��Ҳ�����ȷ��·�ߣ����ǿ��Լ�����poi��
                if (this._pointType == "startPoint" && endStatus == BMAP_ROUTE_STATUS_ADDRESS || this._pointType == "endPoint" && startStatus == BMAP_ROUTE_STATUS_ADDRESS) {
                    this._searchAddress(transitDrive);
                } else {
                    this.dom.panel.address.style.display = "block";
                    this.dom.panel.address.innerHTML = tip;
                }
            }

        },

        /**
         * ���������յ�Ŀ�ѡ��ַ
         */
        _searchAddress: function(transitDrive) {
            var me = this;
            var panel = this.dom.panel;
            if (!this.lsAddress) {
                var renderOptions = {map: this._map};
                if (panel) {
                    renderOptions.panel = this.dom.panel.localSearch;
                }
                this.lsAddress = new BMap.LocalSearch(this._map, {renderOptions: renderOptions});
            }
            var station = me._pointType == "startPoint" ? "�յ�" : "���";
            if (panel) {
                this.dom.panel.address.style.display = "block";
                this.dom.panel.address.innerHTML = "��ѡ��׼ȷ��" + station;
            }
            this.lsAddress.setInfoHtmlSetCallback(function(poi,html){
                var button = document.createElement('div'); 
                button.style.cssText="position:relative;left:50%;margin:5px 0 0 -30px;width:60px;height:27px;line-height:27px;border:1px solid #E0C3A6;text-align:center;color:#B35900;cursor:pointer;background-color:#FFEECC;border-radius:2px; background-image: -webkit-gradient(linear, left top, left bottom, from(#FFFDF8), to(#FFEECC))";
                button.innerHTML = '��Ϊ' + station;
                html.appendChild(button);
                baidu.on(button, "click", function(){
                    me._clearAddress();
                    var nowPoint = poi.marker.getPosition();
                    if (station  == "���") {
                        transitDrive.search(nowPoint, me._point);
                    } else {
                        transitDrive.search(me._point, nowPoint);
                    }
                });
            });
            this._reset();
            this.lsAddress.search(this.dom.transText.value);
        },

        /**
         * ��ȡ�����ݳ������յ�
         */
        _getTransPoi: function(kw) {
            var start, end;

            if (this._pointType == "startPoint") {
                start = this._point;
                end   = kw;
            } else {
                start = kw;
                end   = this._point;
            }

            return {
                "start" : start,
                "end"   : end
            }
        },

        /**
         * ���õ�ǰ���ṩ�ļ�������
         */
        _setSearchTypes: function () {
            var searchTypes = this._unique(this._opts._searchTypes),
                navTab      = this.dom.navTab,
                tabs        = [this.dom.seartTab, this.dom.tohereTab, this.dom.fromhereTab],
                i           = 0,
                len         = 0,
                curIndex    = 0,
                tab;

            this.tabLength = searchTypes.length;
            tabWidth = Math.floor((this._width - this.tabLength + 1) / this.tabLength);
            if (searchTypes.length == 0) {
                //��Ϊ������ʾ�������
                this.dom.navBox.style.display = "none";
            } else {
                for (i = 0, len = tabs.length; i < len; i++) {
                    tabs[i].className = "";
                    tabs[i].style.display = "none";
                }

                for (i = 0; i < this.tabLength; i++) {
                    tab = tabs[searchTypes[i]];
                    if (i == 0) {
                        tab.className = "BMapLib_first BMapLib_current";
                        this._firstTab = tab;
                        curIndex = searchTypes[i];
                    } 
                    if (i == this.tabLength - 1) {
                        //���һ��tab�Ŀ��
                        var lastWidth  = this._width - (this.tabLength - 1) * (tabWidth + 1);
                        if (baidu.browser.ie == 6) {
                            tab.style.width = lastWidth - 3 + "px";
                        } else {
                            tab.style.width = lastWidth + "px";
                        }
                    } else {
                        tab.style.width = tabWidth + "px";
                    }
                    tab.style.display = "block";
                }

                //��������˳������tab
                if (searchTypes[1] != undefined) {
                    navTab.appendChild(tabs[searchTypes[1]])
                }
                if (searchTypes[2] != undefined) {
                    navTab.appendChild(tabs[searchTypes[2]])
                }
                this._showTabContent(curIndex);
            }
            this._adjustTransPosition();
        },

        /**
         * ���û��ṩ�ļ�������ȥ�أ����޳���Ч�Ľ��
         */
        _unique : function (arr) {
            var len = arr.length, 
                result = arr.slice(0), 
                i, 
                datum;
            // �Ӻ���ǰ˫��ѭ���Ƚ�
            // �������Ԫ����ͬ��ɾ����һ��
            while (--len >= 0) { 
                datum = result[len]; 
                if (datum < 0 || datum > 2) {
                    result.splice(len, 1); 
                    continue;
                }
                i = len;
                while (i--) {
                    if (datum == result[i]) { 
                        result.splice(len, 1); 
                        break; 
                    } 
                } 
            }
            return result;
        },

        /**
         * �������Ľ��
         */
        _reset : function () {
            this.localSearch.clearResults();
            this.transitRoute.clearResults();
            this.drivingRoute.clearResults();
            this._closeCircleBound();
            this._hideAutoComplete();
        },

        /**
         * �����ַѡ��ҳ���
         */
        _clearAddress: function() {
            if (this.lsAddress) {
                this.lsAddress.clearResults();
            }
            if (this.dom.panel) {
                this.dom.panel.address.style.display = "none";
            }
        },

        /**
          * IE6�´���PNG��͸��
          * @param {Object} infoWin
          */
        _mendIE6 : function(infoWin){
            if(!baidu.browser.ie || baidu.browser.ie > 6){
                return;
            }
            var popImg = this.container.getElementsByTagName("IMG");
            for(var i = 0; i < popImg.length; i++) {
                if (popImg[i].src.indexOf('.png') < 0) {
                    continue;
                }
                popImg[i].style.cssText += ';FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='+ popImg[i].src +',sizingMethod=crop)'
                popImg[i].src = "http://api.map.baidu.com/images/blank.gif";
            }
        },

        /**
          * ���͵��ֻ�
          */
        _sendToPhone : function(){
            this.showPopup();
        },
        
        /**
         * ������Ϣ��
         */
        showPopup: function() {
            if (!this.pop) {
                this.pop = new Popup(this);
            }
            this._map.addOverlay(this.pop);
        }
    });

    // ��ʾ�뾶���Զ���label
    function RadiusToolBar(point, guid){
        this._point = point;
        this.guid = guid;
    }
    RadiusToolBar.prototype = new BMap.Overlay();
    RadiusToolBar.prototype.initialize = function(map){
        this._map = map;
        var div = this._div = document.createElement("div");

        function stopBubble(e){
            if(e && e.stopPropagation){
                e.stopPropagation();
            }else{
                window.event.cancelBubble = true;
            }
        }
        baidu.on(div, 'mousedown', stopBubble);
        baidu.on(div, 'click', stopBubble);
        baidu.on(div, 'dblclick', stopBubble);
        var searchInfoWindow = BMapLib.SearchInfoWindow.instance[this.guid];
        div.style.cssText = 'position:absolute;white-space:nowrap;background:#fff;padding:1px;border:1px solid red;z-index:99;';
        div.innerHTML = '<input type="text" value="' + searchInfoWindow._radius + '" style="width:30px;" id="BMapLib_search_radius' + this.guid + '"/>m <a href="javascript:void(0)" title="�޸�" onclick="BMapLib.SearchInfoWindow.instance[' + this.guid + ']._changeSearchRadius()" style="font-size:12px;text-decoration:none;color:blue;">�޸�</a><img src="http://api.map.baidu.com/images/iw_close1d3.gif" alt="�ر�" title="�ر�" style="cursor:pointer;padding:0 5px;" onclick="BMapLib.SearchInfoWindow.instance[' + this.guid + ']._closeCircleBound()"/>';
        map.getPanes().labelPane.appendChild(div);
        return div;
    }
    RadiusToolBar.prototype.draw = function(){
        var map = this._map;
        var pixel = map.pointToOverlayPixel(this._point);
        this._div.style.left = pixel.x + 10 + "px";
        this._div.style.top  = pixel.y - 25 + "px";
    }
    

    //��˷����ַ
    var serviceHost = "http://api.map.baidu.com";

    /**
     * �����������
     */
    function Popup(iw){
        this.iw = iw;
    }

    Popup.prototype = new BMap.Overlay();

    baidu.extend(Popup.prototype, {
        initialize : function(map){
            var me = this;
            this._map = map;
            this.container = this.generalDom();
            this._map.getContainer().appendChild(this.container);
            this.initDom();
            this.bind();
            this.getAddressByPoint();
            this.getRememberPhone();
            this.addPhoneNum = 0;
            return this.container; 
        },
        draw : function() {
        },
        generalDom: function() {
            var dom  = document.createElement('div'),
                size = this._map.getSize(),
                top  = 0,
                left = 0;
            if (size.width > 450) {
                left = (size.width - 450) / 2;
            }
            if (size.height > 260) {
                top = (size.height - 260) / 2;
            }
            dom.style.cssText = "position:absolute;background:#fff;width:480px;height:260px;top:" + top + "px;left:" + left + "px;ovflow:hidden;";
            var html = [
                '<div class="BMapLib_sms_tab_container">',
                    '<span>���͵��ֻ�</span>',
                    '<span id="BMapLib_sms_tip" style="display:none;">',
                    '</span>',
                '</div>',
                '<div id="BMapLib_sms_pnl_phone" class="BMapLib_sms_pnl_phone" style="display: block;">',
                    '<div class="BMapLib_ap" id="pnl_phone_left" style="display: block;">',
                        '<table>',
                        	'<tr>',
                        		'<th>���ͷ��ֻ���</th>',
                        		'<td><input type="text" bid="" id="BMapLib_phone_0" maxlength="11" class="BMapLib_sms_input BMapLib_sms_input_l" /><span id="BMapLib_activateTip"></span></td>',
                        	'</tr>',
                        	'<tr id="BMapLib_activateBox" style="display:none;">',
                        		'<th>������</th>',
                        		'<td><input type="text" id="BMapLib_activate" class="BMapLib_sms_input BMapLib_sms_input_s" maxlength="4"/><input type="button" value="��ȡ" id="BMapLib_activate_btn" bid="activate" />',
                        	'</tr>',
                            '<tr>',
                                '<th></th>',
                                '<td>',
                                '</td>',
                            '</tr>',
                        	'<tr>',
                        		'<th style="vertical-align:top;padding-top:7px;">���շ��ֻ���</th>',
                        		'<td><div><input type="text" id="BMapLib_phone_1" class="BMapLib_sms_input BMapLib_sms_input_l" maxlength="11"/><input type="checkbox" id="BMapLib_is_remember_phone"/>��ס�˺�</div>',
                                    '<div id="BMapLib_add_phone_con"></div>',
                                    '<div><a href="javascript:void(0)" id="BMapLib_add_phone_btn" bid="addPhone">����</a></div>',
                                '</td>',
                        	'</tr>',
                        	'<tr>',
                        		'<th></th>',
                        		'<td><input type="button" value="��ѷ��͵��ֻ�" bid="sendToPhoneBtn"/></td>',
                        	'</tr>',
                        '</table>',
                    '</div>',
                  '<div class="BMapLib_mp" id="pnl_phone_right" style="display: block;">',
                          '<div class="BMapLib_mp_title">�������ݣ�</div>',
                          '<div id="BMapLib_msgContent" class="BMapLib_msgContent"></div>',
                  '</div>',
                  '<div style="clear:both;"></div>',
                  '<p id="BMapLib_sms_declare_phone" class="BMapLib_sms_declare_phone">�ٶȱ�֤�����κε������ṩ������ֻ�����</p>',
                  '<div id="tipError" class="tip fail" style="display:none;">',
                    '<span id="tipText"></span>',
                    '<a href="javascript:void(0)" id="tipClose" class="cut"></a>',
                  '</div>',
                  '<div id="sms_lack_tip" style="display:none;">�Ѵ�ÿ��5�ζ�������</div>',
                  '<div id="sms_unlogin_tip" style="display:none;">',
                        '<div style="padding-left:40px;">',
                            '<ul class="login_ul"><li id="normal_login-2" class="login_hover"><a href="javascript:void(0)">�ֻ���¼</a></li></ul>',
                            '<div id="loginBox_02" class="loginBox">',
                                '<div id="pass_error_info-2" class="pass_error_style"></div>',
                                '<div id="passports-2"></div>',
                                '<div id="loginIframe_iph-2" style="display:none"></div>',
                            '</div>',
                        '</div>',
                      '<div class="nopass" style="padding-left:128px;">û�аٶ��ʺţ�<a href="https://passport.baidu.com/v2/?reg&amp;regType=1&amp;tpl=ma" target="_blank">����ע��</a></div>',
                  '</div>',
                '</div>',
                '<button class="BMapLib_popup_close" bid="close"></button>',
                '<div id="BMapLib_success_tip" style="display:none;">���Ķ����Ѿ����͵������ֻ�����ע�����!</div>',

            ].join('');
            dom.innerHTML = html;
            return dom;
        },
        initDom: function() {
            this.dom = {
                sms_tip         : baidu.g('BMapLib_sms_tip'),  //��ʾ��
                activate_btn    : baidu.g('BMapLib_activate_btn'), //��ȡ�����밴ť
                fromphone       : baidu.g("BMapLib_phone_0"),  
                tophone         : baidu.g("BMapLib_phone_1"),
                isRememberPhone : baidu.g("BMapLib_is_remember_phone"),
                sms_container   : baidu.g('BMapLib_sms_pnl_phone'),
                success_tip     : baidu.g('BMapLib_success_tip'), // ���ͳɹ���ʾ��
                add_phone_con   : baidu.g('BMapLib_add_phone_con'),
                add_phone_btn   : baidu.g('BMapLib_add_phone_btn'),
                activateBox     : baidu.g('BMapLib_activateBox'),
                activateTip     : baidu.g('BMapLib_activateTip'),
                activate_input  : baidu.g("BMapLib_activate")
            }
        },
        showTip: function(result) {
            var error = result.error;
            var tipObj = {
                'PHONE_NUM_INVALID'      : '�ֻ�������Ч',
                'SMS_SEND_SUCCESS'       : '���͵��ֻ��ɹ�',
                'AK_INVALID'             : '����ʹ�õ�key��Ч',
                'INTERNAL_ERROR'         : '����������',
                'OVER_MAX_ACTIVATE_TIME' : '�����ѳ������ͼ�����������',
                'SMS_ACTIVATE_SUCCESS'   : '�������ѷ��͵������ֻ�����ע����գ�',
                'ACTIVATE_FAIL'          : '�ֻ���������Ч',
                'SMS_LACK'               : '������������5���ֻ����Ͷ���',
                'PARAM_INVALID'          : '����������ѡ��',
                'SEND_ACTIVATE_FAIL'     : '�����뷢��ʧ��'
            }
            var tip = tipObj[error];

            if (error == 'SMS_LACK') {
                var res_sms = result.res_sms;
                tip = "������������" + res_sms + "���ֻ����Ͷ���";
                this.addPhoneNum = res_sms - 1;
            }

            if (tip) {
                this.dom.sms_tip.innerHTML = tip;
                this.dom.sms_tip.style.display = "inline";
            }
            if (error == 'SMS_SEND_SUCCESS') {
                this.rememberPhone();
                this.sendSuccess();
            }
        },
        //���¼�
        bind: function() {
            var me = this;
            baidu.on(this.container, 'click', function(e) {
                var target = e.target || e.srcElement,
                    bid = target.getAttribute('bid');
                switch (bid) {
                    case 'close':
                        me.closeActon();
                        break;
                    case 'sendToPhoneBtn':
                        me.sendAction();
                        break;
                    case 'activate':
                        me.activateAction();
                        break;
                    case 'addPhone':
                        me.addPhoneAction();
                        break;
                    case 'deletePhone':
                        me.deletePhoneAction(target);
                        break;
                }
            });

            var phone0 = baidu.g('BMapLib_phone_0');
            var phone1 = baidu.g('BMapLib_phone_1');
            //����������ַ���ֻ�������ֺͶ���
            this.container.onkeypress = function (e) {
                var event = e || window.e,
                    keyCode = event.which || event.keyCode,
                    result = false;
                if (keyCode >= 48 && keyCode <= 57 || keyCode == 44 || keyCode == 8) {
                    result = true;
                }
                return result;
            };

            baidu.on(this.dom.fromphone, 'blur', function(){
                if (baidu.isPhone(this.value)) {
                    me.checkActivateAction();
                } else {
                    me.dom.activateTip.innerHTML = "";
                    me.dom.activateBox.style.display = "none";
                }
            });

            baidu.on(this.dom.activate_input, 'blur', function(){
                if (baidu.isActivateCode(this.value)) {
                    me.checkActivateAction();
                } 
            });
        },
        //��֤�ֻ����Ƿ��Ѿ�����
        checkActivateAction: function() {
            var param = {
                phone    : this.dom.fromphone.value,
                activate : this.dom.activate_input.value,
                cbName   : 'callback'
            }
            var me = this;
            this.request(this.config.ckActivateURL, param, function(res){
                if (!res || res.isactivate == false) {
                    //δ����
                    me.dom.activateBox.style.display = "table-row";
                    me.dom.activateTip.style.color = "red";
                    me.dom.activateTip.innerHTML = "δ����";
                } else {
                    //�Ѽ���
                    me.dom.activateBox.style.display = "none";
                    me.dom.activateTip.style.color = "green";
                    me.dom.activateTip.innerHTML = "�Ѽ���";
                }
            });
        },
        //������ť�¼�
        activateAction: function() {
            var me = this;
            var ak = this._map.getKey();
            var params = {
                phone: this.dom.fromphone.value,
                ak  : ak,
                cbName: "callback"
            }
            if (baidu.isPhone(params.phone)) {
                this.request(this.config.activateURL, params, function(result){
                    if (result) {
                        me.showTip(result);
                    }
                });
            } else {
                this.showTip({
                    error: 'PHONE_NUM_INVALID'
                });
            }
        },
        //����رհ�ť�¼�
        closeActon: function() {
            this._map.removeOverlay(this);
        },
        // ��ȡ���ŵ�����
        getMessage: function() {
        },
        // ��ѷ��͵��ֻ�����¼�
        sendAction: function() {
            var me = this;
            if (this.validate()) {
                tophoneStr = baidu.g("BMapLib_phone_1").value;
                var addPhones = this.dom.add_phone_con.getElementsByTagName('input');
                for (var i = 0, len = addPhones.length; i < len; i++) {
                    if (baidu.isPhone(addPhones[i].value)) {
                        tophoneStr += ',' + addPhones[i].value;
                    } else {
                        this.showTip({
                            error: 'PHONE_NUM_INVALID'
                        });
                        return;
                    }
                }
                var ak = this._map.getKey();
                var params = {
                    fromphone   : baidu.g("BMapLib_phone_0").value,  //���ͷ��ֻ�
                    tophone     : tophoneStr,                        //���͵��ֻ�
                    ak          : ak,                               //�û�ak
                    activate    : this.dom.activate_input.value,     //������
                    content     : baidu.g("BMapLib_phone_0").value + "����һ��λ�ø�����" + this.messageContent,
                    cbName      : 'callback'
                };
                this.request(this.config.sendURL, params, function(result){
                    if (result) {
                        me.showTip(result);
                    }
                });
            }
        },
        //�������ݸ�ʽ�Ƿ���ȷ
        validate: function() {
            var flag = true;
            if (!(baidu.isPhone(this.dom.fromphone.value) && baidu.isPhone(this.dom.tophone.value))) {
                flag = false;
                this.showTip({
                    error: 'PHONE_NUM_INVALID'
                });
            };
            return flag;
        },
        getAddressByPoint: function() {
            var pt = this.iw._point,
                me = this,
                gc = new BMap.Geocoder();
            gc.getLocation(pt, function(rs){
                if (rs && rs.addressComponents) {
                    var addComp = rs.addressComponents;
                    me.address = addComp.province + addComp.city + addComp.district + addComp.street + addComp.streetNumber;
                    me.generalMessage();
                }
            });   
        },
        generalMessage: function() {
            var msgContent = baidu.g('BMapLib_msgContent');
            var msg = "";
            var iw = this.iw;
            var point = iw.getPosition();
            if (this.userPhone) {
                msg += this.userPhone + "����һ��λ�ø�����";
            }
            if (iw.getTitle) {
                msg += "����Ϊ��" + iw.getTitle() + "��";
            }
            if (this.address) {
                msg += "����λ����" + this.address + "��";
            }
            var uri = "http://api.map.baidu.com/marker?location=" + point.lat + "," + point.lng + "&title=" + encodeURIComponent(iw.getTitle()) + "&content=" + encodeURIComponent(iw.getContent()) + "&output=html";
            var params = {
                url : encodeURIComponent(uri),
                t   : new Date().getTime(),
                cbName : 'callback'
            };
            var me = this;
            this.request(this.config.shortURL, params, function(result){
                msg += "�鿴��ͼ��" + result.url ? result.url : uri;
                me.messageContent = msg;
                msgContent.innerHTML = msg;
            });
        },
        //��ס�ֻ�����
        rememberPhone: function() {
            if (this.dom.isRememberPhone.checked) {
                var phone = this.dom.tophone.value;
                baidu.cookie.set('BMapLib_phone', phone, {
                    path: '/',
                    expires: 30 * 24 * 60 * 60 * 1000
                });
            }
        },
        //��ȡ��ס���ֻ�����
        getRememberPhone: function() {
            var phone = baidu.cookie.get('BMapLib_phone');
            if (phone) {
                this.dom.tophone.value = phone;
                this.dom.isRememberPhone.checked = true;
            }
        },
        //���ͳɹ���ִ��
        sendSuccess: function() {
            this.dom.sms_container.style.display = "none";
            this.dom.success_tip.style.display = "block";
            var me = this;
            setTimeout(function(){
                me._map.removeOverlay(me);
            }, 1500);
        },
        //�����ֻ����¼�
        addPhoneAction: function() {
            if (this.addPhoneNum >= 4) {
            } else {
                var div = document.createElement('div');
                div.innerHTML = '<input type="text" class="BMapLib_sms_input BMapLib_sms_input_l" maxlength="11"/><a href="javascript:void(0);" style="margin-left:5px;" bid="deletePhone">ɾ��</a>';
                this.dom.add_phone_con.appendChild(div);
                this.addPhoneNum++;
            }
        },
        //ɾ��һ���ֻ����¼�
        deletePhoneAction: function(target){
            target.parentNode.parentNode.removeChild(target.parentNode);
            this.addPhoneNum--;
        },
        //jsonp ����
        request: function(url, params, cbk) {
            // ���������
            var timeStamp = (Math.random() * 100000).toFixed(0);
            // ȫ�ֻص�����
            BMapLib["BMapLib_cbk" + timeStamp] = function(json){
                cbk && cbk(json);
                delete BMapLib["BMapLib_cbk" + timeStamp];
            };

            for (var item in params) {
                if (item != "cbName") {
                    url += '&' + item + "=" + params[item];
                }
            }

            var me = this;
            url += "&" + params.cbName + "=BMapLib.BMapLib_cbk" + timeStamp;
        
            scriptRequest(url);
        },
        config: {
            sendURL       : serviceHost + "/ws/message?method=send",
            activateURL   : serviceHost + "/ws/message?method=activate",
            ckActivateURL : serviceHost + "/ws/message?method=ckActivate",
            shortURL      : "http://j.map.baidu.com/?"
        }
        
    });

    /**
     * script��ǩ����
     * @param {String} url      ����ű�url 
     */
    function scriptRequest(url){    
        var script = document.createElement("script");
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", url);
        // �ű�������ɺ�����Ƴ�
        if (script.addEventListener) {
          script.addEventListener('load', function(e) {
            var t = e.target || e.srcElement;
            t.parentNode.removeChild(t);
          }, false);
        }
        else if (script.attachEvent) {
          script.attachEvent('onreadystatechange', function(e) {
            var t = window.event.srcElement;
            if (t && (t.readyState == 'loaded' || t.readyState == 'complete')) {
              t.parentNode.removeChild(t);
            }
          });
        }
        // ʹ��setTimeout���ie6�޷���������
        setTimeout(function() {
          document.getElementsByTagName('head')[0].appendChild(script);
          script = null;
        }, 1);
    }



    //�����洢����������ʵ��
    var guid = 0;
    BMapLib.SearchInfoWindow.instance = [];
})();